package com.herohead.backup;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import com.herohead.Misc;
import com.herohead.redis.GetRedisServer;
import com.herohead.redis.RedisKeys;
import com.herohead.redis.RedisVars;



public class CloneStatsHome {

	static Jedis jd;
	static Map <Integer, Double> lastValues = new HashMap<Integer, Double>();
	static Map <String, Double> md5Running = new HashMap<String, Double>();
	static Map <String, Double> md5Queued = new HashMap<String, Double>();

	public static String getServer (String hash) {

		String temp = "";
		Map<String, String> mp = jd.hgetAll(hash);

		Iterator it = mp.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry pairs = (Map.Entry)it.next();
			//System.out.println(pairs.getKey() + " = " + pairs.getValue());
			temp = temp + pairs.getValue().toString() + "\n";
			//size = size + Long.parseLong(temp);
		}

		//Misc m = new Misc();

		//String s = m.bytesToMB(String.valueOf(size)) + " MB";

		return temp;
	}


	@SuppressWarnings("rawtypes")
	public static String getSize (String hash) {

		long size = 0;

		Map<String, String> mp = jd.hgetAll(hash);

		Iterator it = mp.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry pairs = (Map.Entry)it.next();
			//System.out.println(pairs.getKey() + " = " + pairs.getValue());
			String temp = pairs.getValue().toString();
			size = size + Long.parseLong(temp);
		}

		Misc m = new Misc();

		String s = m.bytesToMB(String.valueOf(size));

		return s;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//updateValue("del/craigisgreat");

		//System.exit(0);

		Misc m = new Misc();

		GetRedisServer grs = new GetRedisServer();

		//String redisHostName = grs.getRedisHost();
		RedisVars.redisHost = grs.getRedisHost();
		RedisVars.redisHost = "herohead.tzo.net";


		jd = new Jedis(RedisVars.redisHost);

		try {
			if (!grs.checkForRedis(jd)) {
				System.out.println("redis server not found");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		while (true) {
			cls();
			jd = new Jedis(RedisVars.redisHost);
			//jd.connect();
			if (updateRemote(1 ,jd.get("clone:threads:running"))) {
				System.out.print("*");
			}
			System.out.println("Threads running : \t" + jd.get("clone:threads:running"));
			//updateValue("set/" + "clone:threads:running" + "/" + jd.llen(RedisKeys.listProdThreadRunning));
			if (updateRemote(2 ,jd.get("clone:threads:queued"))) {
				System.out.print("*");
			}
			System.out.println("Threads queued : \t" + jd.get("clone:threads:queued"));
			//updateValue("set/" + "clone:threads:queued" + "/" + jd.hlen(RedisKeys.hashProdThreadQueuedProcessID));
			if (updateRemote(3 ,jd.get("clone:threads:completed"))) {
				System.out.print("*");
			}
			System.out.println("Threads completed : \t" + jd.get("clone:threads:completed"));
			//updateValue("set/" + "clone:threads:completed" + "/" + jd.llen(RedisKeys.listProdThreadCompleted));
			//System.out.println("Threads failed : \t" + jd.llen(RedisKeys.listProdThreadFailed));
			//System.out.println("Clones running : \t" + jd.llen("prod:clones:running"));
			System.out.println("----");
			if (updateRemote(4 ,jd.get("clone:clones:running"))) {
				System.out.print("*");
			}
			System.out.println("Clones running : \t" + jd.get("clone:clones:running"));
			//updateValue("set/" + "clone:clones:running" + "/" + jd.llen(RedisKeys.listProdCloneRunning));
			if (updateRemote(5 ,jd.get("clone:clones:completed"))) {
				System.out.print("*");
			}
			System.out.println("Clones completed : \t" + jd.get("clone:clones:completed"));
			//updateValue("set/" + "clone:clones:completed" + "/" + jd.llen(RedisKeys.lProdCloneCompleted));
			if (updateRemote(6 ,jd.get("clone:total:queued:size"))) {
				System.out.print("*");
			}
			System.out.println("Total Queued size : \t" + jd.get("clone:total:queued:size"));
			//updateValue("set/" + "clone:total:queued:size" + "/" + getSize(RedisKeys.hashProdThreadQueuedProcessID));
			if (updateRemote(7 ,jd.get("clone:total:running:size"))) {
				System.out.print("*");
			}
			System.out.println("Total running size : \t" + jd.get("clone:total:running:size"));
			//updateValue("set/" + "clone:total:running:size" + "/" + getSize(RedisKeys.hashProdThreadRunningProcessID));
			if (updateRemote(8 ,jd.get("clone:total:processed:size"))) {
				System.out.print("*");
			}
			System.out.println("Total processed size : \t" + jd.get("clone:total:processed:size"));
			//updateValue("set/" + "clone:total:processed:size" + "/" + getSize(RedisKeys.listProdThreadCompletedProcessID));
			if (updateRemote(9 ,jd.get("clone:ssid:not:cloned"))) {
				System.out.print("*");
			}
			System.out.println("SSID not cloned : \t" + jd.get("clone:ssid:not:cloned"));
			//updateValue("set/" + "clone:ssid:not:cloned" + "/" + jd.scard(RedisKeys.setProdSSIDNotCloned));
			if (updateRemote(10 ,jd.get("clone:groups:not:cloned"))) {
				System.out.print("*");
			}
			System.out.println("Groups not cloned : \t" + jd.get("clone:groups:not:cloned"));
			//updateValue("set/" + "clone:groups:not:cloned" + "/" + jd.scard(RedisKeys.setProdGroupNotCloned));

			//createTempTable(RedisKeys.hashProdThreadRunningProcessID);
			if (updateRemote(11 ,jd.get("clone:smallest:running"))) {
				System.out.print("*");
			}
			System.out.println("Smallest running : \t" + jd.get("clone:smallest:running"));
			//updateValue("set/" + "clone:smallest:running" + "/" + m.bytesToMB(getSmallestInHash(RedisKeys.hashProdThreadRunningProcessID)));
			if (updateRemote(12 ,jd.get("clone:largest:running"))) {
				System.out.print("*");
			}
			System.out.println("Largest running : \t" + jd.get("clone:largest:running"));
			//updateValue("set/" + "clone:largest:running" + "/" + m.bytesToMB(getLargestInHash(RedisKeys.hashProdThreadRunningProcessID)));
			//System.out.println("Smallest running : \t" + (getSmallestInHash(RedisKeys.hashProdThreadRunningProcessID)) + " MB");
			//System.out.println("Largest running : \t" + (getLargestInHash(RedisKeys.hashProdThreadRunningProcessID)) + " MB");
			//jd.del("temp:hash:list");
			//createTempTable(RedisKeys.hashProdThreadQueuedProcessID);
			if (updateRemote(13 ,jd.get("clone:smallest:in:queue"))) {
				System.out.print("*");
			}
			System.out.println("Smallest in Queue : \t" + jd.get("clone:smallest:in:queue"));
			//updateValue("set/" + "clone:smallest:in:queue" + "/" + m.bytesToMB(getSmallestInHash(RedisKeys.hashProdThreadQueuedProcessID)));
			if (updateRemote(14 ,jd.get("clone:largest:in:queue"))) {
				System.out.print("*");
			}
			System.out.println("Largest in Queue : \t" + jd.get("clone:largest:in:queue"));
			//updateValue("set/" + "clone:largest:in:queue" + "/" + m.bytesToMB(getLargestInHash(RedisKeys.hashProdThreadQueuedProcessID)));
			//System.out.println("Smallest in Queue : \t" + (getSmallestInHash(RedisKeys.hashProdThreadQueuedProcessID)) + " MB");
			//System.out.println("Largest in Queue : \t" + (getLargestInHash(RedisKeys.hashProdThreadQueuedProcessID)) + " MB");
			//jd.del("temp:hash:list");
			//System.out.println("Clones Names : \n" + getServer("prod:clones:running:name"));
			//System.out.println("\n-----Clones Names");
			//System.out.println(getServer(RedisKeys.hashProdCloneRunningName));
			//System.out.println("-----Queue Sizes");
			//getQueSizing();
			System.out.println("------Running");

			checkServerList(md5Running,"z_prod:clone:running:size");
			System.out.println("-----Queued");
			checkServerList(md5Queued,"z_prod:clone:queued:size");





			jd.close();

			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


	}

	@SuppressWarnings("null")
	public static String getSmallestInHash(String hash) {



		TreeSet<Long> set = new TreeSet<Long>();

		double d = 0;
		List<String>  s = jd.hvals(hash);
		for (String ss : s) {
			set.add(Long.parseLong(ss));
			//System.out.println(ss);
		}
		if (set.size() == 0) {
			return "0";
		} else {
			return set.first().toString();
		}
		//System.out.println(set.first());
		//String sss = String.valueOf(d);

	}


	public static String getLargestInHash(String hash) {

		TreeSet<Long> set = new TreeSet<Long>();

		double d = 0;
		List<String>  s = jd.hvals(hash);
		for (String ss : s) {
			set.add(Long.parseLong(ss));
			//System.out.println(ss);
		}
		if (set.size() == 0) {
			return "0";
		} else {
			return set.last().toString();
		}
		//System.out.println(set.last());
		//String sss = String.valueOf(d);

	}


	public static void getQueSizing() {

		GetRedisServer grs = new GetRedisServer();

		RedisVars.redisHost = grs.getRedisHost();
		//RedisVars.redisHost = "172.21.5.41";
		RedisVars.redisHost = grs.getHostName();
		Jedis jdro = new Jedis(RedisVars.redisHost,6380);
		Jedis jd = new Jedis(RedisVars.redisHost);
		//System.out.println("Started");
		Set<String> s = jdro.hkeys(RedisKeys.hashProdThreadQueuedProcessID);



		//List<String> runningClones = jdro.hvals(RedisKeys.hashProdCloneRunningName);
		jd.del("z_temp:inprocess:queued:list");
		jd.del("z_temp:inprocess:running:list");
		jd.del("z_temp:inprocess:totalsize");

		for (String processID : s) {

			//System.out.println(processID);
			String command = (jdro.hget(RedisKeys.hashProdThreadQueuedCommand, processID));
			command = command.replace("|", ":");
			//System.out.println(command);
			String cloneName = command.split(":")[0];

			//System.out.println(jdro.hget(RedisKeys.hashProdThreadQueuedProcessID,processID));
			jd.zincrby("z_temp:inprocess:queued:list",1, cloneName);
			jd.zincrby("z_temp:inprocess:totalsize",Double.parseDouble(jdro.hget(RedisKeys.hashProdThreadQueuedProcessID,processID)), cloneName);

		}
		/**
	for (String processID : s) {

		//System.out.println(processID);
		String command = (jdro.hget(RedisKeys.hashProdThreadRunningProcessID, processID));
		command = command.replace("|", ":");
		//System.out.println(command);
		String cloneName = command.split(":")[0];

		//System.out.println(jdro.hget(RedisKeys.hashProdCloneSSID,processID));
		jd.zincrby("z_temp:inprocess:running:list",1, cloneName);

	}

		 **/


		Set<Tuple> tup = jd.zrangeWithScores("z_temp:inprocess:queued:list", 0, -1);
		//Set<Tuple> tupTotal = jd.zrangeWithScores("z_temp:inprocess:totalsize", 0, -1);

		for (Tuple s1 : tup) {
			System.out.print(s1.getElement() + "\t");
			System.out.print(String.format("%.0f",s1.getScore()) + "\t");
			System.out.println(String.format("%.0f",jd.zscore("z_temp:inprocess:totalsize", s1.getElement())/1024/1024));
			//System.out.println(tupTotal     .s1.getElement());
		}

		/**

	for (Tuple s1 : tupTotal) {
		System.out.print("Clone Name : " + s1.getElement() + " ");
		System.out.println(s1.getScore()/1024/1024);
	}

		 **/



		jdro.close();
		jd.close();
	}


	public static void updateValue (String command) {



		try {

			//byte[] encodedBytes = Base64.encodeBase64(Numerous.numeroiusapiUser.getBytes());
			//String userAuth =  new String(encodedBytes);

			//System.out.println(command);
			String url = "http://herohead.tzo.net:7379/" + command;



			//String url = "https://api.numerousapp.com/v1/metrics/2088622069300404688";
			//String url = "https://api.numerousapp.com/v1/users/2088622069300404688/metrics";
			URL obj = new URL(url);
			//System.out.println(obj.getPort());
			//System.out.println(obj.getPath());
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			//con.usingProxy();
			//con.setRequestProperty("Authorization", "Basic " + userAuth);
			//con.setRequestProperty("Content-Type", "application/json");
			System.setProperty("http.proxyHost", "proxy.am.mt.mtnet");
			System.setProperty("http.proxyPort", "8080");
			//con.setRequestProperty("http:proxyHost", "proxy.am.mt.mtnet");
			//con.setRequestProperty("http:proxyPort", "8080");
			con.setRequestMethod("PUT");

			//con.setDoOutput(true);

			//JSONObject jobj = new JSONObject();
			//jobj.put("value", value);
			//jobj.put("description", "cool it works - again");
			//jobj.put("units", "kgs");

			//System.out.println(jobj.toJSONString());
			//System.out.println(jobj.toString());

			//System.exit(0);

			//String data = jobj.toJSONString();

			//String data =  "{\"value\":\"99\"}";
			con.getContent();

			//OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
			//out.write(data);
			//out.close();

			// new InputStreamReader(con.getInputStream());

			BufferedReader in = new BufferedReader(
					new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
			//System.out.println(response.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}


	}
	public static boolean updateRemote(int indexNumber ,String value) {
		boolean updated = false;

		if (value == null) {return false;}
		try {
			double lastV;


			double passV = Double.parseDouble(value);

			if (lastValues.containsKey(indexNumber)) {
				lastV = lastValues.get(indexNumber);
				lastValues.put(indexNumber, passV);
				if (lastV != passV) {
					//System.out.println("Something changed " + key);
					//updateValue("set/" + key + "/" + value);
					updated=true;;
				}
			} else {
				lastValues.put(indexNumber, passV);
				//System.out.println("Something changed " + key);
				//updateValue("set/" + key + "/" + value);
				updated = true;
			}

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			return false;
		}
		return updated;

	}
	public static void cls()
	{
		for( int i = 0; i < 25; i++ ) {
			System.out.println("");
		}
	}

	public static boolean checkServerList(Map <String, Double>passedMap, String key) {

		Double lastV;
		//System.out.println("In ServerList");
		Set<Tuple> runningSize = jd.zrevrangeWithScores(key, 0, -1);
		Boolean updated = false;

		Misc m = new Misc();

		for (Tuple d : runningSize) {
			String el = d.getElement();
			double score = d.getScore();
			//System.out.println(el + ":" + score);
			if (passedMap.containsKey(el)) {
				lastV = passedMap.get(el);

				//System.out.println(lastV);
				//System.out.println(lastV);
				if (lastV != score) {
					//System.out.println("Something changed " + key);
					System.out.println("*" + el + "\t" + String.format("%.0f", score/1024/1204));
					passedMap.put(el, score);
					updated=true;
				} else {
					System.out.println(el + "\t" + String.format("%.0f", score/1024/1204));
				}
			} else {
				passedMap.put(el, score);
				//System.out.println("Something changed " + key);
				System.out.println("*" + el + "\t" + String.format("%.0f", score/1024/1204));
				updated = true;
			}



		}

		return updated;

	}
}
